<template>
  <div :style="style" style="display: block;" v-show="show" class="right-menu"
    @mousedown.stop
    @contextmenu.prevent
  >
    <template v-for="item in data">
      <a href="javascript:" @click="click(item.type)">{{item.name}}</a>
    </template>
  </div>
</template>

<script>
export default {
  name: 'mg-context-menu',
  data () {
    return {
      triggerShowFn: () => {},
      triggerHideFn: () => {},
      x: null,
      y: null,
      style: {},
      binded: false
    }
  },
  props: {
    target: null,
    show: Boolean,
    data: {
      type: Array,
      default: () => []
    }
  },
  mounted () {
    this.bindEvents(this.target)
  },
  watch: {
    show (show) {
      if (show) {
        this.bindHideEvents()
      } else {
        this.unbindHideEvents()
      }
    },
    target (newVal, oldVal) {
      this.unbindEvents(oldVal)
      this.bindEvents(newVal)
    }
  },
  methods: {
    // 初始化事件
    bindEvents (newVal) {
      this.$nextTick(() => {
        if (!newVal) return
        this.triggerShowFn = this.contextMenuHandler.bind(this)
        newVal.addEventListener('contextmenu', this.triggerShowFn)
      })
    },

    // 取消绑定事件
    unbindEvents (oldVal) {
      if (!oldVal) return
      oldVal.removeEventListener('contextmenu', this.triggerShowFn)
    },

    // 绑定隐藏菜单事件
    bindHideEvents () {
      this.triggerHideFn = this.clickDocumentHandler.bind(this)
      document.addEventListener('mousedown', this.triggerHideFn)
      document.addEventListener('mousewheel', this.triggerHideFn)
    },

    // 取消绑定隐藏菜单事件
    unbindHideEvents () {
      document.removeEventListener('mousedown', this.triggerHideFn)
      document.removeEventListener('mousewheel', this.triggerHideFn)
    },

    // 鼠标按压事件处理器
    clickDocumentHandler (e) {
      this.$emit('update:show', false)
    },

    // 右键事件事件处理
    contextMenuHandler (e) {
      this.x = e.clientX
      this.y = e.clientY
      this.layout()
      this.$emit('update:show', true)
      e.preventDefault()
    },

    // 布局
    layout () {
      this.style = {
        left: this.x + 'px',
        top: this.y + 'px'
      }
    },

    // 点击事件
    click (type) {
      this.$emit('click', type)
    }
  }
}
</script>

<style>
  .right-menu {
    position: fixed;
    background: #fff;
    border: solid 1px rgba(0, 0, 0, .2);
    border-radius: 3px;
    z-index: 999;
    box-shadow: 0 0.5em 1em 0 rgba(0,0,0,.1);
  }
  .right-menu a {
    width: 75px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    display: block;
    color: #1a1a1a;
    padding: 2px;
    text-decoration: none;
  }
  .right-menu a:hover {
    background: #42b983;
    color: #fff;
  }
</style>
